package com.cwnu.controller;

import com.cwnu.entity.Article;
import com.cwnu.entity.PageBean;
import com.cwnu.entity.Result;
import com.cwnu.entity.User;
import com.cwnu.service.AdminService;
import com.cwnu.service.UserService;
import com.cwnu.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/admin")
public class AdminController {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private AdminService adminService;

    @Autowired
    private UserService userService;
    @PostMapping("/userlist")
    public Result getUserList(@RequestBody Map<String, Object> params) {
        Integer pageNum = (Integer) params.get("pageNum");
        Integer pageSize = (Integer) params.get("pageSize");
        String username = (String) params.get("username");
        if (username != null) {
            username = '%' +username + '%';
        }
        PageBean<User> userList = adminService.getUserList(pageNum, pageSize, username);
        return Result.success(userList);
    }

    @DeleteMapping("/deleteUser/{userId}")
    public Result deleteUser(@PathVariable Integer userId) {
        adminService.deleteUser(userId);
        return Result.success();
    }

    @PostMapping("/login")
    public Result adminLogin(@RequestBody Map<String, Object> params) {
        String username = (String) params.get("username");
        String password = (String) params.get("password");
        // 先查询用户是否存在
        User loginUser = userService.findByUserName(username);
        if (loginUser == null) {
            return Result.error("用户名不存在，请重试");
        }
        // 判断密码是否正确
        if (password.equals(loginUser.getPassword()) && loginUser.getRole() == 1) {
            // 登录成功
            Map<String, Object> claims = new HashMap<>();
            claims.put("id", loginUser.getId());
            claims.put("username", loginUser.getUsername());
            String token = JwtUtil.genToken(claims);
            // 登录之后，向redis中注入新的token
            ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
            operations.set(token, token, 1, TimeUnit.DAYS);
            return Result.success(token);
        }
        return Result.error("密码错误！");
    }

    @DeleteMapping("/logout")
    public Result adminLogout(@RequestHeader("Authorization") String token) {
//        System.out.println(token);
        if (token == null) {
            return Result.error("未携带有效Token");
        }
//        token = token.substring(7); // 去除Bearer前缀

        // 2. 删除Redis中对应的Token键
        boolean deleted = Boolean.TRUE.equals(stringRedisTemplate.delete(token));
        if (deleted) {
            return Result.success();
        } else {
            return Result.error("退出失败：Token不存在或已过期");
        }
    }
}
